package com.tanhao.takeaway.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhao.takeaway.commom.R;
import com.tanhao.takeaway.entity.category;
import com.tanhao.takeaway.entity.dish;
import com.tanhao.takeaway.entity.dishDto;
import com.tanhao.takeaway.entity.dishFlavor;
import com.tanhao.takeaway.service.categoryService;
import com.tanhao.takeaway.service.dishFlavorService;
import com.tanhao.takeaway.service.dishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class dishController {
    @Autowired
    private dishFlavorService dishServiceFlavor;

    @Autowired
    private dishService dishservice;

    @Autowired
    private dishFlavorService dishflavorservice;

    @Autowired
    private categoryService categoryservice;

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody dishDto d) {
        dishservice.saveDishWithFlavor(d);
                Set key=redisTemplate.keys("dish_*");
       redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<dish> page1 = new Page<>(page, pageSize);
        LambdaQueryWrapper<dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(name != null, dish::getName, name);
        dishservice.page(page1, lambdaQueryWrapper);
        Page<dishDto> dishDtoPage = new Page<>();
        BeanUtils.copyProperties(page1, dishDtoPage, "records");
        List<dish> records = page1.getRecords();
        List<dishDto> list = records.stream().map((item) -> {
                    dishDto dto = new dishDto();
                    BeanUtils.copyProperties(item, dto);
                    Long categoryId = item.getCategoryId();
                    category c = categoryservice.getById(categoryId);
                    if (c != null) {
                        String name1 = c.getName();
                        dto.setCategoryName(name1);
                    }
                    return dto;
                }
        ).collect(Collectors.toList());

        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);

    }

    @GetMapping("/{id}")
    public R<dishDto> get(@PathVariable Long id) {
        dishDto byIdWithFlavor = dishservice.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }

    @PutMapping
    public R<String> update(@RequestBody dishDto d) {
        dishservice.updateWithFlavor(d);
//        Set key=redisTemplate.keys("dish_*");
//        redisTemplate.delete(key);

        String key="dish_"+d.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("修改菜品成功");
    }

//    @DeleteMapping
//    public R<String> delete(Long ids){
//        dishservice.removeById(ids);
//        return R.success("删除菜品成功");
//    }


    @PostMapping("/status/{s}")
    public R<String> updateStatus(@RequestParam("ids") List<Long> ids, @PathVariable int s) {
//        LambdaQueryWrapper<dish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(ids!=null,dish::getId,ids);
//        dish one = dishservice.getOne(lambdaQueryWrapper);
       Set key=redisTemplate.keys("dish_*");
       redisTemplate.delete(key);

        ids.stream().map((item) -> {
            if (s == 0) {
                UpdateWrapper<dish> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", item);
                updateWrapper.set("status", 0);
                dishservice.update(updateWrapper);
            }
            if (s == 1) {

                UpdateWrapper<dish> updateWrapper1 = new UpdateWrapper<>();
                updateWrapper1.eq("id", item);
                updateWrapper1.set("status", 1);
                dishservice.update(updateWrapper1);
            }
            return 1;
        }).collect(Collectors.toList());

//        if(s==0){
//            UpdateWrapper<dish> updateWrapper=new UpdateWrapper<>();
//            updateWrapper.eq("id",ids);
//            updateWrapper.set("status",0);
//            dishservice.update(updateWrapper);
//        }
//        if(s==1){
//
//            UpdateWrapper<dish> updateWrapper1=new UpdateWrapper<>();
//            updateWrapper1.eq("id",ids);
//            updateWrapper1.set("status",1);
//            dishservice.update(updateWrapper1);
//        }
        return R.success("菜品状态修改成功");
    }


    @DeleteMapping
    public R<String> delete(@RequestParam("ids") List<Long> ids) {
//        List<dish> dishCollect = ids.stream().map((item) -> {
//            dish d = dishservice.getById(item);
//            return d;
//        }).collect(Collectors.toList());
//
        ids.stream().map((item) -> {
            dishservice.removeById(item);
            LambdaQueryWrapper<dishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<dishFlavor>();
            lambdaQueryWrapper.eq(dishFlavor::getDishId, item);
            dishflavorservice.remove(lambdaQueryWrapper);

            return 1;
        }).collect(Collectors.toList());


        return R.success("批量删除成功");
    }

    @GetMapping("/list")
    public R<List<dishDto>> list(dish d){
         String key="dish_"+d.getCategoryId()+"_"+d.getStatus();
        List<dishDto> cache = (List<dishDto>) redisTemplate.opsForValue().get(key);
        if(cache!=null){
            return R.success(cache);
        }

        //构造查询条件
        LambdaQueryWrapper<dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(d.getCategoryId() != null, dish::getCategoryId, d.getCategoryId());
        //添加条件，查询状态为1（1为起售，0为停售）的菜品
        queryWrapper.eq(dish::getStatus,1);

        List<dish> list = dishservice.list(queryWrapper);


        List<dishDto> collect = list.stream().map((item) -> {
            dishDto dto = new dishDto();
            BeanUtils.copyProperties(item, dto);
            Long categoryId = item.getCategoryId();  //分类id
            //通过categoryId查询到category内容
            category c = categoryservice.getById(categoryId);
            //判空
            if(c != null){
                String categoryName = c.getName();
                dto.setCategoryName(categoryName);
            }

            Long dishId = item.getId();
            LambdaQueryWrapper<dishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(dishFlavor::getDishId, dishId);
            List<dishFlavor> list1 = dishflavorservice.list(lambdaQueryWrapper);
            dto.setFlavors(list1);
            return dto;
        }).collect(Collectors.toList());

        redisTemplate.opsForValue().set(key,collect,60, TimeUnit.MINUTES);
        return R.success(collect);
    }
}
